package com.cn.dlr.zk.案例1;

import org.apache.zookeeper.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: dlr
 * @data: 2019/8/7 22:50
 * @desc: 服务器集群(3台,注册到zk集群),zk动态感知服务器的上下线,在通过客户端获取上下线信息
 */
public class ServerRemove {
    //连接地址
    private static final String connectString = "192.168.10.20:2181,192.168.10.30:2181,192.168.10.40:2181";
    //session 会话
    private static final int sessionTimeout = 2000;
    ZooKeeper zooKeeper;
    public static void main(String[] args) throws Exception{
        ServerRemove client=new ServerRemove();
        //连接zk服务器
        client.getZkConeection();
        //向zk注册本服务
        client.getServers();
        //执行业务逻辑(让进程不要死掉,就回代表一个服务器开启状态)
        client.doWork();
    }

    //连接zk服务器
    private void getZkConeection() throws Exception {
        zooKeeper= new ZooKeeper(connectString, sessionTimeout, new Watcher(){
            @Override
            public void process(WatchedEvent event) {
               try{
                   getServers();
               }
               catch (Exception e){
                   e.printStackTrace();
               }
            }
        });
    }

    //向zk监听节点服务
    private void getServers() throws Exception{
        List<String> childNodes=zooKeeper.getChildren("/servers",true);
        List<String> lists=new ArrayList<>();
        for(String child:childNodes){
            byte[] data = zooKeeper.getData("/servers/" + child, false, null);
            lists.add(new String(data));
        }
        System.out.println("当前在线主机:"+lists);
    }

    private void doWork() throws Exception{
        Thread.sleep(Long.MAX_VALUE);
    }
}
